import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shortmovieapp/common.dart';
import 'package:shortmovieapp/data/requestData.dart';
import 'package:shortmovieapp/data/viewData.dart';
import 'package:shortmovieapp/http/request/appRequest.dart';
import 'package:shortmovieapp/myPages/shareView.dart';

class movieEidtPage extends StatefulWidget {
  final MovieData data;
  const movieEidtPage.movieEditPage({super.key, required this.data});

  @override
  State<movieEidtPage> createState() => _movieEidtPageState();
}

class _movieEidtPageState extends State<movieEidtPage> {
  final ImagePicker _picker = ImagePicker();
  File? videoPicked;

  late MovieData data;

  @override
  void initState() {
    data = widget.data;

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        iconTheme: const IconThemeData(
          color: Colors.black, // 设置返回箭头的颜色
        ),
        backgroundColor: Colors.white,
        titleTextStyle: const TextStyle(fontSize: 18, color: Colors.black),
        title: const Text("合集"),
        centerTitle: true,
        actions: [
          TextButton(
              onPressed: () => onClickEditInfo(context),
              child: const Text(
                "修改信息",
                style: TextStyle(color: Colors.black54),
              ))
        ],
      ),
      body: Container(
        //padding: const EdgeInsets.fromLTRB(10, 20, 10, 0),
        child: Column(
          children: [
            addMovieInfoRow(),
            const SizedBox(height: 10),
            const Divider(
                height: 15,
                thickness: 5,
                color: Color.fromARGB(100, 221, 221, 221)),
            const SizedBox(height: 10),
            Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
              child: const Text(
                "视频列表",
                style: TextStyle(color: Colors.black),
              ),
            ),
            addVideoListView(),
            const SizedBox(height: 10),
            Container(
              width: 120,
              height: 40,
              child: ElevatedButton(
                  onPressed: () => onClickUpload(context),
                  style: const ButtonStyle(
                      backgroundColor:
                          MaterialStatePropertyAll(Colors.deepOrange),
                      foregroundColor: MaterialStatePropertyAll(Colors.white)),
                  child: const Text(
                    "上传视频",
                    style: TextStyle(fontSize: 15),
                  )),
            ),
          ],
        ),
      ),
    );
  }

  Widget addVideoListView() {
    int count = data.videoDatas.length;
    Debug.log("videoDatas count:$count");
    if (count <= 0) {
      return Container(
        height: 150,
        alignment: Alignment.bottomCenter,
        child: const Text(
          "合集内暂无视频",
          style: TextStyle(color: Colors.grey),
        ),
      );
    }
    return Container(
        height: 150,
        alignment: Alignment.topCenter,
        child:ListView.builder(
        scrollDirection: Axis.vertical,
        itemCount: count,
        itemBuilder: (context, index) {
          var videoData = data.videoDatas[index];

          return Container(
            padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
            height: 40,
            child: Stack(
              children: [
                Align(
                  alignment: Alignment.centerLeft,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        videoData.title!,
                        style: const TextStyle(color: Colors.black),
                      ),
                      Text(
                        videoData.publishedDate.toString(),
                        style: const TextStyle(color: Colors.grey),
                      ),
                    ],
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child:
                Text(videoData.approved ? "已过审" : "视频审核中",
                    style: const TextStyle(color: Colors.black))
                )
              ],
            ),
          );
        })
    );
  }

  Container addMovieInfoRow() {
    return Container(
      padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
      alignment: Alignment.center,
      height: 100,
      child: Row(
        children: [
          Container(
            width: 80,
            height: 100,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                image: DecorationImage(
                    image: NetworkImage(data.info.iconUrl),
                    fit: BoxFit.cover)),
          ),
          Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.fromLTRB(20, 0, 0, 0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 30,
                    child: Text(
                      data.info.title,
                      style: const TextStyle(
                          fontSize: 16,
                          color: Colors.black,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                  Text(
                    data.info.desc,
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                  Text(data.info.typeName,
                      style: const TextStyle(fontSize: 12, color: Colors.grey))
                ],
              ))
        ],
      ),
    );
  }

  void onClickEditInfo(BuildContext context) {
    Debug.log("onClickEditInfo ");
  }

  void onClickUpload(BuildContext context) async {
    Debug.log("onClickUpload ");

    final pickedImage = await _picker.pickVideo(source: ImageSource.gallery);
    if (pickedImage != null) {
      var file = File(pickedImage.path);
      videoPicked = file;

      // ignore: use_build_context_synchronously
      showUplopadDialog(context,
          "${data.info.title}${data.videoDatas.length + 1}");
    }
  }

  void showUplopadDialog(BuildContext context, String content) async {
    await showDialog(
        barrierDismissible: true, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return VideoUploadDialog(
              onConfirm: (cont, inputVlaue) {
                if (isStringEmpty(inputVlaue)) {
                  return;
                }
                Debug.log("确定上传");
                uploadVideo(context,inputVlaue!);
              },
              content: content);
        });
  }

  void uploadVideo(BuildContext cont,String inputVlaue) async {
    var mdata = data;
    VideoProto protp = VideoProto(mdata.info.movieId, mdata.info.title,
        mdata.videoDatas.length + 1, inputVlaue);
    var req = uploadVideoRequest(protp);
    var response = await req.sendFile(videoPicked!.path);

    if (response.suc) {
      String responseData = response.data ?? "{}";
      MovieData movieData = MovieData.fromJsonString(responseData);

      Debug.log("上传视频成功:$movieData");
      Future(() {
          Navigator.of(cont).pop();

          setState(() {
            data = movieData;
          });
      });
    } else {
      Debug.log("上传视频失败:${response.message}");
    }
  }
}

class VideoUploadDialog extends Dialog {
  String? content;
  Function(BuildContext context, String? inputValue)? onConfirm;
  VideoUploadDialog({Key? key, required this.onConfirm, this.content = ""})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
          child: Container(
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10), color: Colors.white),
        height: 300,
        width: 220,
        child: Column(
          children: <Widget>[
            const Padding(
              padding: EdgeInsets.all(10),
              child: Align(
                alignment: Alignment.center,
                child: Text("视频上传", style: TextStyle(color: Colors.black)),
              ),
            ),
            const Divider(),
            Container(
                padding: const EdgeInsets.all(10),
                height: 180,
                width: double.infinity,
                child: MyInput(
                  textColor: Colors.black,
                  cursorColor: Colors.black45,
                  hint: "视频标题",
                  initialText: content,
                  onValueChanged: (value) {
                    content = value;
                    Debug.log("on value changed:$value");
                  },
                )
                // Text(content,
                //   textAlign: TextAlign.left,
                //   style: const TextStyle(color: Colors.black),
                // ),
                ),
            Container(
              decoration:
                  BoxDecoration(borderRadius: BorderRadius.circular(10)),
              width: 200,
              height: 40,
              child: ElevatedButton(
                onPressed: () => onConfirm?.call(context, content),
                child: const Text("确定"),
              ),
            )
          ],
        ),
      )),
    );
  }
}
